import router from './router'
import type { RouteRecordRaw } from 'vue-router'
import { formatRoutes } from './utils/router'
import { useAuthStore } from '@/store';
import { App } from 'vue';


// 路由加载前
router.beforeEach(async (to, from, next) => {
  const { menus } = useAuthStore()
  const routerList = formatRoutes(menus)
  routerList.forEach((route) => {
    router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
  })
  next()
})

// 路由跳转之后调用
router.afterEach((to) => { })

/* 按钮权限 */
export function hasPermi(app: App<Element>) {
  app.directive('hasPermi', (el, binding) => {
    const { permissions } = useAuthStore()
    const { value } = binding
    const all_permission = '*:*:*'

    if (value && value instanceof Array && value.length > 0) {
      const permissionFlag = value

      const hasPermissions = permissions.some((permission: string) => {
        return all_permission === permission || permissionFlag.includes(permission)
      })

      if (!hasPermissions) {
        el.parentNode && el.parentNode.removeChild(el)
      }
    } else {
      throw new Error('权限不存在')
    }
  })
}

export const setupAuth = (app: App<Element>) => {
  hasPermi(app)
}